package com.elite.groovy.callback;

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util;
import com.elite.groovy.kh.KHDBConfig
import com.elite.groovy.kh.LogToDB
import com.elite.groovy.kh.KHUtil

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.text.SimpleDateFormat;
import org.springframework.jdbc.core.JdbcTemplate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @projectName: ngsapitask-davco
 * @package: com.elite.groovy.callback*
 * @className: apiGetCustomer
 * @author: tian*
 * @description: 获取用户信息，写入本地，返回customer_guid
 * @date: 2023-08-15 14:00
 * @version: 1.0
 */
public class apiGetCustomer implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiGetCustomer.class);
    private static String classString = "apiGWRelayProxy";
    private static String Customer_Guid = "";
    private static String selectSQL = "";
    private static String updateSQL = "";
    private static JdbcTemplate jt = null;

    private String Re_CustID, Re_CustomerName, Re_Mobile, Re_CustID2, Re_Source,Re_Customer_ID;//参数定义

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        // 调用IP过滤
        if (KHDBConfig.getParam(eliteBean, "#APIIP") == "1" && !KHUtil.getRemoteHost(request)) {
            log.warn("API被非法IP调用-Request Not Allow!");
            return "Request Not Allow!";
        }

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        // 获取数据源
        jt = new JdbcTemplate(eliteBean.getDataSource());
        String logMessage = "开始时间：" + startTime + System.getProperty("line.separator");

        // 初始化返回参数
        String Syncpram = "";
        JSONObject Retupram = new JSONObject();

        String getMethod = request.getMethod();
        if (getMethod.equals("GET")) {
            Syncpram = request.getQueryString();
            log.info("接口服务" + classString + " 接收调用GET参数信息：" + Syncpram);
        } else if (getMethod.equals("POST")) {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                Syncpram += line;
            }

            log.info("接口服务" + classString + " 接收调用POST报文信息：" + System.getProperty("line.separator") + Syncpram);
        }

        //处理请求参数
        try {
            JSONObject inJson = JSONObject.fromObject(Syncpram);

            //参数处理
            Re_CustID = KHUtil.GetSFJV(inJson, "CustID");     //客户证号
            Re_CustomerName = KHUtil.GetSFJV(inJson, "CustomerName");     //客户姓名
            Re_Mobile = KHUtil.GetSFJV(inJson, "Mobile");     //手机号码
            Re_CustID2 = KHUtil.GetSFJV(inJson, "CustID2");     //身份证号
            Re_Source = KHUtil.GetSFJV(inJson, "Source");     //查询来源
            Re_Customer_ID = KHUtil.GetSFJV(inJson, "Customer_ID");     //boos的客户ID

            //参数校验
            if (KHUtil.isNull(Re_CustID) && KHUtil.isNull(Re_CustomerName) && KHUtil.isNull(Re_Mobile) && KHUtil.isNull(Re_CustID2)&& KHUtil.isNull(Re_Customer_ID)) {
                Retupram.put("respCode", "-1");
                Retupram.put("respDesc", "调用失败:请传递查询参数值");
                Retupram.put("result", "");
                return Retupram;
            }
            if (KHUtil.isNull(Re_Source)) {
                Retupram.put("respCode", "-1");
                Retupram.put("respDesc", "调用失败:请传递来源参数值");
                Retupram.put("result", "");
                return Retupram;
            }

            //主方法
            if (Re_Source.equals("CUST")) {
                Retupram = getYNBossInfo(eliteBean, Re_CustID, Re_CustID2, Re_CustomerName, Re_Mobile, Re_Source,Re_Customer_ID);
            } else if (Re_Source.equals("WORK")) {
                Retupram = WorkCustInfo(eliteBean, Re_CustID, Re_CustID2, Re_CustomerName, Re_Mobile, Re_Source,Re_Customer_ID);
            }

        } catch (Exception e) {
            log.error("处理系统Customer信息异常:", e)
            Retupram.put("respCode", "-99");
            Retupram.put("respDesc", "处理系统Customer信息异常-" + e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "内部调用", "apiSysCustDealCore", Syncpram, Retupram.toString(), (System.currentTimeMillis() - startTime).toString(), logMessage);
        }

        return Retupram;

    }

    // 工单获取客户信息调用
    private static JSONObject WorkCustInfo(EliteBean eliteBean, String Re_CustID, String Re_CustID2, String Re_CustomerName, String Re_Mobile, String Re_Source,String Re_Customer_ID) {
        JSONObject result = new JSONObject();
        //todo 乐购乐销信息调用
        //getYNBossInfo(eliteBean, Re_CustID, Re_CustID2, Re_CustomerName, Re_Mobile, Re_Source,Re_Customer_ID);

        try {

            List EliteCustArr = eliteBean.chaxun_sql("Select c.customer_guid,c.customername from customer c where 1=1 And (mobile='" + Re_Mobile + "' or others='" + Re_Mobile + "')", "dataSource");
            //本地查到Cust,执行update
            if (EliteCustArr.size() > 0) {
                result.put("respCode", "200");
                result.put("data", EliteCustArr);
                result.put("respDesc", "更新成功！");
                return result;

            }
            //本地未查到Cust，执行insert
            else if (EliteCustArr.size() == 0) {
                String Customer_Guid = "GDWORK-" + KHUtil.getRandomString(29).toUpperCase();
                eliteBean.update("insert into customer(customer_guid,mobile,customername,sourcesys,createdby,createddate) values('" + Customer_Guid + "','" + Re_Mobile + "','" + Re_CustomerName + "','" + Re_Source + "','SELITE',now())", "dataSource");
                List EliteCustinsert = eliteBean.chaxun_sql("Select c.customer_guid,c.customername from customer c  where 1=1 And (mobile='" + Re_Mobile + "' or others='" + Re_Mobile + "')", "dataSource");
                result.put("respCode", "200");
                result.put("data", EliteCustinsert);
                result.put("respDesc", "写入成功！");
                return result;
            }

        } catch (Exception e) {
            log.error("数据处理错误", e);
            result.put("respCode", "-99");
            result.put("respDesc", "请校验参数！");
            return result;
        }

    }

    // todo 调用乐购乐销接口获取信息
    private static JSONObject getYNBossInfo(EliteBean eliteBean, String markno, String cardno, String cust_name, String access_num, String op_Source,String Re_Customer_ID) {
        JSONObject resultJson = new JSONObject();
        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        String injson = "";
        String bossResult = "";
        String logMessage = "getYNBossInfo开始时间：" + startTime + System.getProperty("line.separator");

        // 获取数据源
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        try {
            //获取配置信息
            String YNBossURL = KHDBConfig.getAPIURL(eliteBean, "YNBossURL");
            String YNBossURLParam = KHDBConfig.getParamConfig(eliteBean, "YNBossURLParam");// 交互参数:version|system|deptid|clientcode|clientpwd|citycode
            String[] YNBossURLParamArr = YNBossURLParam.split("\\|");
            String version = YNBossURLParamArr[0];//版本编号，填 1
            String system = YNBossURLParamArr[1];//外围系统标识，BOSS 分配，客服系统传 2
            String deptid = YNBossURLParamArr[2];//操作员所在部门
            String clientcode = YNBossURLParamArr[3];// BOSS 预先配置
            String clientpwd = YNBossURLParamArr[4];//BOSS 预先配置，调用时通过 MD5 加密，md5 加密为 32 位的密文
            String citycode = YNBossURLParamArr[5];//操作员所在地市
            log.debug("getYNBossInfo YNBossURL:" + YNBossURL + "	version:" + version + "	system:" + system + "	deptid:" + deptid + "	clientcode:" + clientcode + "	clientpwd:" + clientpwd);

            String servicecode = "GW_CC_QRYCUSTINFO";

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String date = simpleDateFormat.format(new Date());
            Random random = new Random();
            int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000000;

            String requestid = clientcode.toLowerCase() + date + rannum;
            log.debug("生成的请求ID:" + requestid);

            //生成请求内容
            JSONObject infojson = new JSONObject();
            if (!KHUtil.isNull(markno)) {
                infojson.put("markno", markno);
            }
            if (!KHUtil.isNull(cardno)) {
                infojson.put("cardno", cardno);
            }
            if (!KHUtil.isNull(cust_name)) {
                infojson.put("cust_name", cust_name);
            }
            if (!KHUtil.isNull(access_num)) {
                infojson.put("access_num", access_num);
            }
            if (!KHUtil.isNull(Re_Customer_ID)) {
                infojson.put("cust_id", Re_Customer_ID);
            }
            infojson.put("channel_id", "2000");
            infojson.put("pagesize", "10");
            infojson.put("currentPage", 1);
            log.debug("生成请求内容:" + infojson.toString());

            HashMap<String, String> paramHashMap = new HashMap<String, String>();
            paramHashMap.put("version", version);
            paramHashMap.put("system", system);
            paramHashMap.put("citycode", citycode);
            paramHashMap.put("deptid", deptid);
            paramHashMap.put("clientcode", clientcode);
            paramHashMap.put("clientpwd", clientpwd);
            paramHashMap.put("servicecode", servicecode);
            paramHashMap.put("requestid", requestid);
            paramHashMap.put("requestContent", infojson.toString());

            injson = KHUtil.SplicingMap(paramHashMap, "&");
            log.debug("待发送参数信息:" + injson);

            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            bossResult = Util.doHttpPostUseHead(YNBossURL, injson, "UTF-8", 60000, 0, headMap);
            logMessage = logMessage + "调用国网耗时(毫秒):" + (System.currentTimeMillis() - endTime) + System.getProperty("line.separator");
            log.debug("调用返回结果:" + bossResult);

            //解析SSO返回信息
            JSONObject bossResultJson = JSONObject.fromObject(bossResult);
            String status = KHUtil.GetSFJV(bossResultJson, "status");
            String message = KHUtil.GetSFJV(bossResultJson, "message");
            String output = KHUtil.GetSFJV(bossResultJson, "output");

            log.debug("返回结果解析Status:" + status + " 返回流水RequestID:" + requestid + " 返回Message:" + message);
            if (status.equals("0")) {
                JSONObject outputJson = JSONObject.fromObject(output);
                JSONArray custlistArr = new JSONArray();
                if (outputJson.containsKey("custlist")) {
                    custlistArr = outputJson.getJSONArray("custlist");
                }

                int custlistArrSize = custlistArr.size();

                for (int i = 0; i < custlistArrSize; i++) {
                    JSONObject customerJson = custlistArr.getJSONObject(i);

                    String re_custid = KHUtil.GetSFJV(customerJson, "custid");//客户编号
                    String re_cust_id = KHUtil.GetSFJV(customerJson, "cust_id");//国网客户ID
                    String re_markno = KHUtil.GetSFJV(customerJson, "markno");//客户证号
                    String re_custstatus = KHUtil.GetSFJV(customerJson, "custstatus");//客户状态
                    String re_cust_name = KHUtil.GetSFJV(customerJson, "cust_name");//客户名称
                    String re_cont_number = KHUtil.GetSFJV(customerJson, "cont_number");//联系电话
                    String re_phone = KHUtil.GetSFJV(customerJson, "phone");//手机
                    String re_cardtype = KHUtil.GetSFJV(customerJson, "cardtype");//证件类型
                    String re_cardno = KHUtil.GetSFJV(customerJson, "cardno");//证件号码
                    String re_service = KHUtil.GetSFJV(customerJson, "service");//客户级别
                    String re_custtype = KHUtil.GetSFJV(customerJson, "custtype");//客户类型
                    String re_linkaddr = KHUtil.GetSFJV(customerJson, "linkaddr");//客户地址
                    String re_areaid = KHUtil.GetSFJV(customerJson, "areaid");//服务区域
                    String re_kgcustid = "";

                    String bossType = !KHUtil.isNull(re_custid) ? "YNBOSS" : !KHUtil.isNull(re_cust_id) ? "GWBOSS" : "MOBILE";

                    List<Map<String, Object>> selectArr = null;
                    if (bossType == "GWBOSS") {
                        selectSQL = '''Select c.Customer_Guid, c.Customertype2_Id From Customer c Where Customertype2_Id = ?''';
                        selectArr = jt.queryForList(selectSQL, re_cust_id);

                    } else if (bossType == "YNBOSS") {
                        selectSQL = '''Select c.Customer_Guid, c.Customerid2 From Customer c Where Customerid2 = ?''';
                        selectArr = jt.queryForList(selectSQL, re_custid);

                    } else if (bossType == "KGBOSS") {
                        selectSQL = '''Select c.Customer_Guid, c.Stringfield1 From Customer c Where Stringfield1 = ?''';
                        selectArr = jt.queryForList(selectSQL, re_kgcustid);

                    }
                    //本地查到Cust,执行update
                    if (selectArr.size() > 0) {
                        Customer_Guid = selectArr.get(0).get("Customer_Guid");
                        updateSQL = '''Update Customer
                                       Set Customer_Id     = ?,
                                           Customer_State  = ?,
                                           Customername    = ?,
                                           Mobile          = ?,
                                           Others          = ?,
                                           Idtype          = ?,
                                           Customerid      = ?,
                                           Customer_Level  = ?,
                                           Customertype_Id = ?,
                                           Address         = ?,
                                           Area            = ?,
                                           Datatype        = ?,
                                           Customertype2_Id= ?,
                                           Stringfield1    = ?,
                                           Modifiedby      = 'APICUS',
                                           Modifieddate    = Now()
                                     Where Customer_Guid = ?''';
                        int updateNum = jt.update(updateSQL, re_markno, re_custstatus, re_cust_name, re_phone, re_cont_number, re_cardtype, re_cardno, re_service, re_custtype, re_linkaddr, re_areaid, bossType, re_cust_id, re_kgcustid, Customer_Guid);
                        log.debug("根据省网Boss返回数据更新Customer Customer_Guid:" + Customer_Guid + " 更新Customer结果:" + updateNum);

                    } else if (selectArr.size() == 0) {
                        Customer_Guid = bossType + KHUtil.getRandomString(29).toUpperCase();
                        updateSQL = '''Insert Into Customer
                                          (Customer_Guid,
                                           Customerid2,
                                           Customer_Id,
                                           Customer_State,
                                           Customername,
                                           Mobile,
                                           Others,
                                           Idtype,
                                           Customerid,
                                           Customer_Level,
                                           Customertype_Id,
                                           Address,
                                           Area,
                                           Datatype,
                                           Customertype2_Id,
                                           Stringfield1,
                                           Createdby,
                                           Createddate,
                                           Modifiedby,
                                           Modifieddate)
                                        Values
                                          (?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           ?,
                                           'APICUS',
                                           Now(),
                                           'APICUS',
                                           Now())''';
                        int updateNum = jt.update(updateSQL, Customer_Guid, re_custid, re_markno, re_custstatus, re_cust_name, re_phone, re_cont_number, re_cardtype, re_cardno, re_service, re_custtype, re_linkaddr, re_areaid, bossType, re_cust_id, re_kgcustid);
                        log.debug("根据省网Boss返回数据新增Customer Customer_Guid:" + Customer_Guid + " 新增Customer结果:" + updateNum);

                    }

                    JSONArray user_infos = customerJson.getJSONArray("user_infos");
                    for (int j = 0; j < user_infos.size(); j++) {
                        JSONObject user_infoJson = user_infos.getJSONObject(j);

                        String u_serv_id = KHUtil.GetSFJV(user_infoJson, "serv_id");
                        String u_access_num = KHUtil.GetSFJV(user_infoJson, "access_num");
                        String u_state = KHUtil.GetSFJV(user_infoJson, "state");
                        String u_areaid = KHUtil.GetSFJV(user_infoJson, "areaid");
                        String u_city = KHUtil.GetSFJV(user_infoJson, "city");
                        String u_permark = KHUtil.GetSFJV(user_infoJson, "permark");
                        String u_addr = KHUtil.GetSFJV(user_infoJson, "addr");
                        String u_logicdevno = KHUtil.GetSFJV(user_infoJson, "logicdevno");
                        String u_areaname = KHUtil.GetSFJV(user_infoJson, "areaname");
                        String u_cityname = KHUtil.GetSFJV(user_infoJson, "cityname");

                        String userType = !KHUtil.isNull(u_serv_id) ? "YNBOSS" : !KHUtil.isNull(u_access_num) ? "MOBILE" : "OTHERS";

                        List<Map<String, Object>> bossArr = null;
                        if (userType == "YNBOSS") {
                            selectSQL = '''Select Boss_Guid From Customer_Boss Where Customer_Guid = ? And Serv_Id = ?''';
                            bossArr = jt.queryForList(selectSQL, Customer_Guid, u_serv_id);

                        } else if (userType == "MOBILE") {
                            selectSQL = '''Select Boss_Guid From Customer_Boss Where Customer_Guid = ? And Access_Num = ?''';
                            bossArr = jt.queryForList(selectSQL, Customer_Guid, u_access_num);

                        } else if (userType == "OTHERS") {
                            selectSQL = '''Select Boss_Guid From Customer_Boss Where Customer_Guid = ? And Concat(Ifnull(Serv_Id, ''), Ifnull(Access_Num, ''), Ifnull(Logicdevno, '')) = Concat(Ifnull(?), Ifnull(?), Ifnull(?))''';
                            bossArr = jt.queryForList(selectSQL, Customer_Guid, u_serv_id, u_access_num, u_logicdevno);

                        }
                        log.debug("查询Customer_Boss结果:" + bossArr.toString());

                        //本地查到Cust,执行update
                        if (bossArr.size() > 0) {
                            String Boss_Guid = bossArr.get(0).get("Boss_Guid");
                            String updateSQL = '''Update Customer_Boss
                                                       Set Boss_Type     = ?,
                                                           Serv_Id       = ?,
                                                           Access_Num    = ?,
                                                           State         = ?,
                                                           Areaid        = ?,
                                                           City          = ?,
                                                           Permark       = ?,
                                                           Addr          = ?,
                                                           Logicdevno    = ?,
                                                           Modifiedby    = 'APICUS',
                                                           Modifieddate  = Now(),
                                                           Areaname  = ?,
                                                           Cityname  = ?
                                                     Where Boss_Guid = ?''';
                            int updateNum = jt.update(updateSQL, bossType, u_serv_id, u_access_num, u_state, u_areaid, u_city, u_permark, u_addr, u_logicdevno, u_areaname, u_cityname, Boss_Guid);
                            log.debug("根据省网Boss返回数据更新Customer Customer_Guid:" + Customer_Guid + " 影响数据:" + updateNum);

                        } else if (bossArr.size() == 0) {
                            String updateSQL = '''Insert Into Customer_Boss
                                                      (Boss_Guid,
                                                       Customer_Guid,
                                                       Boss_Type,
                                                       Serv_Id,
                                                       Access_Num,
                                                       State,
                                                       Areaid,
                                                       City,
                                                       Permark,
                                                       Addr,
                                                       Logicdevno,
                                                       Createdby,
                                                       Createddate,
                                                       Modifiedby,
                                                       Modifieddate,
                                                       Areaname,
                                                       Cityname)
                                                    Values
                                                      (Uuid(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'APICUS', Now(), 'APICUS', Now(), ?, ?)''';
                            int updateNum = jt.update(updateSQL, Customer_Guid, bossType, u_serv_id, u_access_num, u_state, u_areaid, u_city, u_permark, u_addr, u_logicdevno, u_areaname, u_cityname);
                            log.debug("根据省网Boss返回数据新增Customer Customer_Guid:" + Customer_Guid + " 影响数据:" + updateNum);

                        }

                    }

                }

                resultJson.put("respCode", "1");
                resultJson.put("respDesc", "处理成功！");
                resultJson.put("customer_guid", Customer_Guid);
                resultJson.put("data", custlistArr);

            } else {

                resultJson.put("respCode", "-1");
                resultJson.put("respDesc", "省网Boss调用处理异常-错误码[" + status + "] 错误描述[" + message + "]");
                resultJson.put("data", []);
            }
        } catch (Exception e) {
            logMessage = logMessage + "系统调用Boss客户信息接口异常:" + e.getMessage() + " 调用国网耗时(毫秒):" + (System.currentTimeMillis() - startTime) + System.getProperty("line.separator");
            log.error("系统API-系统调用Boss客户信息接口异常", e);

            resultJson.put("respCode", "-1");
            resultJson.put("respDesc", "省网Boss调用处理异常-" + e.getMessage());
            resultJson.put("data", []);
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "客户资料API-调用省网Boss", "GW_CC_QRYCUSTINFO", injson, bossResult, (System.currentTimeMillis() - startTime).toString(), logMessage);
        }
        log.debug("调用Boss返回处理后信息:" + resultJson.toString());
        return resultJson;
    }


}